﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Properties;
using ConfExpert.Utility;

using ConfExpert.Utility.Peripheral;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class StokKarti : XForm
    {
        bool wQty = false;
        public StokKarti(bool _wQty)
        {
            InitializeComponent();
            wQty = _wQty;
        }

        private RepositoryItemGridLookUpEdit riDesen
        {
            get
            {
                DataTable idle = new DataTable();
                idle.Columns.Add("Id", typeof(int));
                idle.Columns.Add("Desc", typeof(string));

                RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.DataSource = idle;
                ri.DisplayMember = "Desc";
                ri.ValueMember = "Id";
                ri.NullText = " ";
                ri.View.PopulateColumns();

                int idx = 0;
                foreach (string str in ";1- Düz;2- Küçük kareli;3- Büyük Kareli;4- Kalın Çizgili;5- İnce Çizgi;6- Baskılı".Split(";".ToCharArray()))
                    idle.Rows.Add(idx++, str);

                ri.View.BestFitColumns();
                return ri;
            }
        }

        bool yetkili;
        BindingSource bsProduct, bsUK, bsMK;
        private void StokKarti_Load(object sender, EventArgs e)
        {
            yetkili = ytk(141);

            splitContainerControl3.AcKapa(false);

            TAM.ProductTableAdapter = new ConfExpert.Datasets.MyDataTableAdapters.ProductTableAdapter();
            TAM.UreticiKodlariTableAdapter = new Datasets.MyDataTableAdapters.UreticiKodlariTableAdapter();
            TAM.MusteriKodlariTableAdapter = new Datasets.MyDataTableAdapters.MusteriKodlariTableAdapter();

            if (!ds.Product.Columns.Contains("CurrentQty"))
            {
                ds.Product.Columns.Add("CurrentQty", typeof(decimal), "SUM(Child(FK_xStok_Product_ProductId).Qty)");
                //ds.Product.Columns.Add("Desen", typeof(int), "MAX(Child(FK_xStok_Product_ProductId).Desen)");
                ds.Product.Columns.Add("M", typeof(string), "MAX(Child(FK_xStok_Product_ProductId).M)");
                ds.Product.Columns.Add("AnlasilanEur", typeof(decimal), "MAX(Child(FK_xStok_Product_ProductId).AnlasilanEur)");
                ds.Product.Columns.Add("TotalEur", typeof(decimal), "CurrentQty*AnlasilanEur");
            }

            if (yetkili)
                ds.Product.Columns.Add("Sec", typeof(bool));

            bsProduct = new BindingSource(ds, "Product");
            bsUK = new BindingSource(bsProduct, "FK_UreticiKodlari_Product_ProductId");
            bsMK = new BindingSource(bsProduct, "FK_MusteriKodlari_Product_ProductId");
            AddBsToList(bsProduct, bsUK, bsMK);


            InitGridView(gvProduct, bsProduct);

            gvProduct.Columns["ProductId"].ColumnEdit = new RepositoryItemTextEdit();

            gvProduct.MakeColumnInvisible("PRO");
            gvProduct.Columns["ProductId"].Visible = true;

            gvProduct.Columns["M"].ToolTip = "Muadili Var mı?";


            //foreach (string Message in ";1- Düz;2- Küçük kareli;3- Büyük Kareli;4- Kalın Çizgili;5- İnce Çizgi;6- Baskılı".Split(";".ToCharArray()))
            //    riDesen.Items.Add(Message);
            //riDesen.TextEditStyle = TextEditStyles.DisableTextEditor;
            //gvProduct.Columns["Desen"].ColumnEdit = riDesen;

            if (!yetkili)
                gvProduct.MakeReadOnly();

            gvProduct.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvProduct.OptionsView.ShowViewCaption = false;

            btnKartAc.ItemClick += BtnKartAc_ItemClick;
            btnKaydet.ItemClick += BtnKaydet_ItemClick;
            btnGuncelle.ItemClick += BtnGuncelle_ItemClick;
            btnScan.ItemClick += BtnScan_ItemClick;
            btnScanBig.ItemClick += BtnScanBig_ItemClick;
            btnMerge.Visibility = ytk(190) ? BarItemVisibility.Always : BarItemVisibility.Never;
            btnMerge.ItemClick += btnMerge_ItemClick;

            ds.Product.TableNewRow += new DataTableNewRowEventHandler(Product_TableNewRow);

            gcProduct.ShowOnlyPredefinedDetails = true;


            barManager.ForceLinkCreate();
            barManager.ItemClick += new ItemClickEventHandler(barManager_ItemClick);

            PopupMenu newPopup3 = new PopupMenu(barManager);
            newPopup3.Name = "Actions";
            foreach (string str in "&Muadil Kumaşlar;&Tarayıcı Seç;&Etiket Düzenle".Split(';'))
            {
                BarButtonItem bbi = new BarButtonItem(barManager, str, 0, BarShortcut.Empty);

                bbi.Name = str;
                bbi.GroupIndex = 1;
                //bbi.AllowAllUp = true;
                bbi.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Default;

                newPopup3.AddItems(new BarItem[] { bbi });
            }
            ddb.DropDownControl = newPopup3;
            ddb.Visibility = isAdmin ? BarItemVisibility.Always : BarItemVisibility.Never;


            GridManager gm = GridManager.GetManager(gvUK);
            gm.GridMenu.AddMenu("Bu satırdaki üreticiyi ORJİNAL ÜRETİCİ olarak işaretle", MakeOrgVendor_Click);
            gm.GridMenu.AddMenu("ORJİNAL ÜRETİCİ bilgisini kaldır", CleanOrgVendor_Click);


            GridManager gm2 = GridManager.GetManager(gvProduct);
            //gm2.GridMenu.AddMenu("Bu artikele yakın renkler", YakinRenkler);
            //gm2.GridMenu.AddMenu("TinEye ile eşleştir", TinyEyeEslestir, Resources.Colors_16x16, true);
            //gm2.GridMenu.AddMenu("Renge göre sırala", RengeGoreSirala);
            //gm2.GridMenu.AddMenu("Resim Yükle", UploadPhoto);
            if (ytk(144))
                gm2.GridMenu.AddMenu("Başka bir artikelin resmini kopyala", CopyScanFrom_Click);
            gm2.GridMenu.AddMenu("Teknik özellikleri güncelle", Teknik);
            gm2.GridMenu.AddMenu("Bu artikelin HAREKETLERİ", HareketleriGoster);
            gm2.GridMenu.AddMenu("MUADİL kumaşları göster", MuadilGoster);
            gm2.GridMenu.AddMenu("Benzer kumaşları göster", FindSimilar, Resources.CustomerReports_Icon);
            if (ytk(146))
                gm2.GridMenu.AddMenu("Benzer kumaşları göster (TEST)", FindSimilar3);

            if (yetkili)
            {
                gm2.GridMenu.AddMenu("Seç", SatirSec, Resources.Plus_16x16, true);
                gm2.GridMenu.AddMenu("Bırak", SatirBirak, Resources.Minus_16x16);
                gm2.GridMenu.AddMenu("Kalite etiketi bas", PrintKaliteEtiket, null);
                gm2.GridMenu.AddMenu("Arşiv etiketi bas", PrintArsivEtiket, null);
            }

            InitCheckedComboBox();


            gvProduct.RowCellStyle += new RowCellStyleEventHandler(gvProduct_RowCellStyle);
            gvProduct.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(gvProduct_FocusedRowChanged);


            //gvProduct.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle; // <<< NEW LINE

            splitContainerControl3.SizeChanged += new EventHandler(splitContainerControl3_SizeChanged);
            sccKodlar.AutoSize();

            //gleKons = GetIntellisensedRI(AppSession.MainForm.dtKons);
            //gleEn = GetIntellisensedRI(AppSession.MainForm.dtEn);
            //gleAgr = GetIntellisensedRI(AppSession.MainForm.dtAgr);

            //gvProduct.Columns["Konstruksiyon"].ColumnEdit = gleKons;
            //gvProduct.Columns["EnGrubu"].ColumnEdit = gleEn;
            //gvProduct.Columns["Agirlik"].ColumnEdit = gleAgr;

            //((RepositoryItemGridLookUpEdit)gvProduct.Columns["Konstruksiyon"].ColumnEdit).ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
            //((RepositoryItemGridLookUpEdit)gvProduct.Columns["EnGrubu"].ColumnEdit).ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
            //((RepositoryItemGridLookUpEdit)gvProduct.Columns["Agirlik"].ColumnEdit).ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
            //((RepositoryItemGridLookUpEdit)gvProduct.Columns["KaliteId"].ColumnEdit).Closed += new ClosedEventHandler(StokKarti_Closed);
            gvProduct.CellValueChanged += gvProduct_CellValueChanged;

            gvProduct.RowStyle += new RowStyleEventHandler(gvProduct_RowStyle);

            //gvProduct.FocusedRowHandle = gvProduct.LocateByDisplayText(0, gvProduct.Columns["ProductId"], ProductId.ToString());
            //gvProduct.TopRowIndex = gvProduct.FocusedRowHandle;

            InitGridView(gvUK, bsUK);
            gvUK.MakeColumnInvisible("UreticiKodlariId", "Scan", "ProductId");
            gvUK.MakeEditable();
            gvUK.EnableNewRow();
            gvUK.RowCellStyle += gvUK_RowCellStyle;
            gvUK.Columns["KaliteAciklama"].VisibleIndex = gvUK.Columns["UreticiKodu"].VisibleIndex + 1;

            InitGridView(gvMK, bsMK);
            gvMK.MakeColumnInvisible("MusteriKodlariId", "Scan", "ProductId");
            gvMK.MakeEditable();
            gvMK.EnableNewRow();
            gvMK.RowCellStyle += gvMK_RowCellStyle;

            //tabInner.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;

            //gvMK.DoubleClick += new EventHandler(gvMK_DoubleClick);

            ds.MusteriKodlari.TableNewRow += new DataTableNewRowEventHandler(MusteriKodlari_TableNewRow);

            if (wQty)
            {
                gvProduct.YanYanaGetirSoluna("Desc7C", "AnlasilanEur", "CurrentQty", "TotalEur", "M");
                gvProduct.Columns["CurrentQty"].ColumnEdit = new RepositoryItemCalcEdit();
                gvProduct.FormatAsNumber(1, "CurrentQty", "TotalEur");
                gvProduct.FormatAsNumber(3, "AnlasilanEur");
                gvProduct.AddSummary("CurrentQty", "TotalEur");
            }
            else
                gvProduct.AddSummary();

            if (yetkili)
                gvProduct.YanYanaGetir("Sec:ProductId");


            //(gvProduct.Columns["Scan"].ColumnEdit as RepositoryItemPictureEdit).Padding = new System.Windows.Forms.Padding(-1);

            RefreshData();

            btnMK.CheckedChanged += btnMK_CheckedChanged;

            ds.UreticiKodlari.TableNewRow += UreticiKodlari_TableNewRow;
            gvMK.Columns["UserId"].OptionsColumn.AllowEdit = false;
            gvUK.Columns["UserId"].OptionsColumn.AllowEdit = false;

            foreach (DataRow r in AppSession.Lookups.V_User.Select("DepartmentId = 26", string.Empty))
                DestexUsers.Add(r["UserId"].ToInt());

            gvProduct.ShowingEditor += gvProduct_ShowingEditor;

            gvProduct.MakeColumnInvisible("ProductId");

            //ProductId-PRO dönüşümü yapılmaması gerektiği için extension kullanılmadı            
            gvProduct.Columns["ProductId"].VisibleIndex = 0;
            gvProduct.Columns["Scan"].VisibleIndex = 1;
            gvProduct.Columns["Name"].VisibleIndex = 2;

            gvProduct.BestFitColumns();
        }
        List<int> DestexUsers = new List<int>();

        void gvProduct_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !(MyDept == 26 && DestexUsers.Contains(gvProduct.GetFocusedRowCellValue("UserId").ToInt()) && gvProduct.GetFocusedRowCellValue("ProductId").ToInt() > 70000 || MyDept != 26);
        }

        void gvProduct_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName == "KaliteId")
            {
                gvProduct.EndEditing();
                KaliteChanged(gvProduct.FocusedRowHandle);
            }
        }

        void btnMerge_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (MergeStokKarti m = new MergeStokKarti())
                if (m.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    ExecuteNonQuery("ExecQuery", m.query);
        }

        private void PrintArsivEtiket(object sender, EventArgs e)
        {
            PrintEtiket(1);
        }

        private void PrintKaliteEtiket(object sender, EventArgs e)
        {
            PrintEtiket(2);
        }

        private void PrintEtiket(int Tip)
        {
            gvProduct.EndEditing();
            string ProductIds = "";
            foreach (MyData.ProductRow dr in ds.Product.Select("Sec=1"))
                ProductIds += dr.ProductId.ToString() + ",";

            ProductIds = ProductIds.RemoveIfEndsWith(",");
            if (ProductIds == "")
            {
                ShowErrorMessage("Lütfen etiket almak istediğiniz kumaşları seçin");
                return;
            }

            using (ArsivEtiketi ne = new ArsivEtiketi(ProductIds, Tip, "GetKaliteEtiketiByProductId"))
                ne.ShowDialog();
        }

        private void SatirBirak(object sender, EventArgs e)
        {
            foreach (int handle in gvProduct.GetSelectedRows())
                gvProduct.SetRowCellValue(handle, "Sec", false);
        }

        private void SatirSec(object sender, EventArgs e)
        {
            foreach (int handle in gvProduct.GetSelectedRows())
                gvProduct.SetRowCellValue(handle, "Sec", true);
        }


        void UreticiKodlari_TableNewRow(object sender, System.Data.DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
        }

        void btnMK_CheckedChanged(object sender, EventArgs e)
        {
            splitContainerControl3.AcKapa(btnMK.Checked);
        }

        private void BtnScanBig_ItemClick(object sender, ItemClickEventArgs e)
        {
            bool big = (XtraMessageBox.Show("Bu seçenek, rapor boyu 10 cm.'den büyük kumaşlar içindir. Rapor boyu 10 cm.'den büyük mü?", "Dikkat", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes);

            if (bsProduct.Count > 0)
            {
                if (gvProduct.GetFocusedRowCellValue("Scan") != null)
                    if (XtraMessageBox.Show("Bu varyant için daha önce taranmış bir görüntü var. Üzerine yazmak ister misiniz?", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;

                Scan(big);
            }
        }


        void FindSimilar(object sender, EventArgs e)
        {
            int productID = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
            FindSimilarBenzerRenk(productID);
        }

        void FindSimilar3(object sender, EventArgs e)
        {
            int productID = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
            FindSimilarBenzerRenk(productID, 3);
        }

        DateTime LastUpdate = new DateTime(2000, 1, 1);

        private void BtnGuncelle_ItemClick(object sender, ItemClickEventArgs e)
        {
            RefreshData();
        }

        private void RefreshData()
        {
            ds.xDate.Clear();
            ds.xStok.Clear();
            GetDetails("Product;UreticiKodlari;MusteriKodlari;xDate;xStok", "GetStokYeni", LastUpdate, wQty);
            LastUpdate = ds.xDate[0].Tarih;
        }

        /*
        private void btnUpload_Click(object sender, EventArgs e)
        {
            Save();
            int productId = intParse(gvProduct.GetRowCellValue(gvProduct.FocusedRowHandle, "ProductId"));
            if (fdPicture.ShowDialog() == DialogResult.OK)
            {
                byte[] pic = File.ReadAllBytes(fdPicture.FileName);
                Image image;
                using (MemoryStream inStream = new MemoryStream())
                {
                    inStream.Write(pic, 0, pic.Length);
                    image = Bitmap.FromStream(inStream);
                }

                Image photoLarge = resizeImage(image, new Size(375, 375));
                Image photo = cropImage(photoLarge, new Rectangle(20, 20, 75, 75));
                Image photoMikro = resizeImage(photo, new Size(32, 32));

                MemoryStream msphotoLarge = new MemoryStream();
                MemoryStream msphotoMikro = new MemoryStream();
                MemoryStream msphoto = new MemoryStream();

                photoLarge.Save(msphotoLarge, ImageFormat.Png);
                byte[] bPhotoLarge = msphotoLarge.ToArray();
                msphotoLarge.Dispose();

                photoMikro.Save(msphotoMikro, ImageFormat.Png);
                byte[] bphotoMikro = msphotoMikro.ToArray();
                msphotoMikro.Dispose();

                photo.Save(msphoto, ImageFormat.Png);
                byte[] bphoto = msphoto.ToArray();
                msphoto.Dispose();

                GetDetails("Product", "UpdPhoto", productId, pic, bPhotoLarge, bphotoMikro, bphoto);
                gvProduct.RefreshData();
                //gvProduct.SetFocusedRowCellValue("PhotoMikro", bphotoMikro);
                //gvProduct.SetFocusedRowCellValue("Photo", bphoto);
            }
        }
        */
        private void CopyScanFrom_Click(object sender, EventArgs e)
        {
            Save();
            using (CopyScanFrom cs = new CopyScanFrom(ProductId))
                if (cs.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    RefreshData();
        }

        void HareketleriGoster(object sender, EventArgs e)
        {
            int productId = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
            if (productId > 0)
                using (DepoStokHareketler rzv = new DepoStokHareketler(productId))
                    rzv.ShowDialog();
        }

        void MuadilGoster(object sender, EventArgs e)
        {
            int productId = bsProduct.GetCurrentValue("ProductId").ToInt(-1);
            if (productId > 0)
                using (Equiv eq = new Equiv(productId))
                    eq.ShowDialog();
        }

        void MusteriKodlari_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
        }

        //void RengeGoreSirala(object sender, EventArgs e)
        //{
        //    gvProduct.SortInfo.ClearAndAddRange(new GridColumnSortInfo[] { 
        //            new GridColumnSortInfo(gvProduct.Columns["Hue"], ColumnSortOrder.Ascending)
        //            });
        //    gvProduct.RefreshData();
        //}

        void gvMK_DoubleClick(object sender, EventArgs e)
        {
            using (Araclar.Brand2Customer b = new Araclar.Brand2Customer())
            {
                if (b.ShowDialog() == DialogResult.OK)
                {
                    if (gvMK.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                        gvMK.SetFocusedRowCellValue("CustomerId", b.CustomerId);
                    else
                    {
                        ConfExpert.Datasets.MyData.MusteriKodlariRow mkr = ds.MusteriKodlari.NewMusteriKodlariRow();
                        mkr.ProductId = ProductId;
                        mkr.CustomerId = b.CustomerId;
                        ds.MusteriKodlari.AddMusteriKodlariRow(mkr);
                    }

                    gvMK.BestFitColumns();
                }
            }
        }

        void MakeOrgVendor_Click(object sender, EventArgs e)
        {
            GetDetails("UreticiKodlari", "UpdUK", intParse(bsUK, "UreticiKodlariId"), true);
        }

        void CleanOrgVendor_Click(object sender, EventArgs e)
        {
            GetDetails("UreticiKodlari", "UpdUK", intParse(bsUK, "UreticiKodlariId"), false);
        }

        //void SetVal(string f, object val)
        //{
        //    gvProduct.SetFocusedRowCellValue(f, val);
        //}

        /*
        void StokKarti_Closed(object sender, ClosedEventArgs e)
        {
            //gvProduct.EndEdit();
            //KaliteChanged(gvProduct.FocusedRowHandle);      
        }
    */
        void Teknik(object sender, EventArgs e)
        {
            gvProduct.EndEditing();
            foreach (int rowHandle in gvProduct.GetSelectedRows())
                if (rowHandle > -1)
                    KaliteChanged(rowHandle);
        }

        void KaliteChanged(int rh)
        {
            if (rh > -1)
            {
                DataRow r = gvProduct.GetDataRow(rh);
                int KaliteId = r["KaliteId"].ToInt();
                if (KaliteId > 0)
                {
                    gvProduct.SetRowCellValue(rh, "KaliteAciklama", null);

                    MyData.KaliteRow kr = AppSession.Lookups.Kalite.FindByKaliteId(KaliteId);

                    if (!kr.IsVendorIdNull())
                        gvProduct.SetRowCellValue(rh, "KVendorId", kr.VendorId);
                    else
                        gvProduct.SetRowCellValue(rh, "KVendorId", null);

                    if (!kr.IsFinishIdNull())
                        gvProduct.SetRowCellValue(rh, "FinishId", kr.FinishId);
                    //else
                    //    SetVal("FinishId", null);

                    if (!kr.IsKompozisyonIdNull())
                        gvProduct.SetRowCellValue(rh, "KompozisyonId", kr.KompozisyonId);
                    else
                        gvProduct.SetRowCellValue(rh, "KompozisyonId", null);

                    if (!kr.IsKonstruksiyonNull())
                        gvProduct.SetRowCellValue(rh, "Konstruksiyon", kr.Konstruksiyon);
                    else
                        gvProduct.SetRowCellValue(rh, "Konstruksiyon", null);

                    if (!kr.IsEnGrubuNull())
                        gvProduct.SetRowCellValue(rh, "EnGrubu", kr.EnGrubu);
                    //else
                    //    SetVal("EnGrubu", null);

                    if (!kr.IsAgirlikNull())
                        gvProduct.SetRowCellValue(rh, "Agirlik", kr.Agirlik);
                    //else
                    //    SetVal("Agirlik", null);

                    if (!kr.IsGrupESPIdNull())
                        gvProduct.SetRowCellValue(rh, "GrupESPId", kr.GrupESPId);
                    //else
                    //    SetVal("GrupESPId", null);

                    if (!kr.IsFabricTypeIdNull())
                        gvProduct.SetRowCellValue(rh, "FabricTypeId", kr.FabricTypeId);
                    else
                        gvProduct.SetRowCellValue(rh, "FabricTypeId", null);
                }
            }
        }


        void gvUK_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (e.Column.FieldName.Contains("VendorId"))
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);

                if (gvUK.GetRowCellValue(e.RowHandle, "isOriginal") != null)
                    if (gvUK.GetRowCellValue(e.RowHandle, "isOriginal") != DBNull.Value)
                        if ((bool)gvUK.GetRowCellValue(e.RowHandle, "isOriginal"))
                            e.Appearance.BackColor = System.Drawing.Color.LightBlue;
            }
        }

        void gvMK_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
                if (e.Column.FieldName.Contains("BrandId"))
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        void gvProduct_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gv = sender as GridView;
            if (e.RowHandle >= 0)
                if (gv.GetRowCellValue(e.RowHandle, "Deleted") != null)
                    if (gv.GetRowCellValue(e.RowHandle, "Deleted") != DBNull.Value)
                        if ((bool)gv.GetRowCellValue(e.RowHandle, "Deleted") == true)
                        {
                            e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Strikeout);
                            e.Appearance.ForeColor = Color.Gray; // SystemColors.ControlDark;
                        }
        }

        void splitContainerControl3_SizeChanged(object sender, EventArgs e)
        {
            splitContainerControl3.SplitterPosition = splitContainerControl3.Width / 3 * 2;

            //vgc.RecordWidth = splitContainerControl2.Panel1.Width - vgc.RowHeaderWidth - 3;
        }


        void gvProduct_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle > -1)
            {
                ProductId = intParse(bsProduct, "ProductId");
                if (ds.Product.FindByProductId(ProductId) != null)
                    txtInfo.Caption = ds.Product.FindByProductId(ProductId).Name;
                else
                    txtInfo.Caption = string.Empty;
            }
            //pivotGridControl1.Fields["ProductId"].BestFit();
        }

        void gvProduct_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                GridView view = sender as GridView;
                if (intParse(view.GetRowCellValue(e.RowHandle, "ProductId")) == ProductId && ProductId > 0)
                    e.Appearance.BackColor = System.Drawing.Color.YellowGreen;
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

                switch (e.Column.FieldName)
                {
                    case "Name":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }
            }

        }


        RepositoryItemCheckedComboBoxEdit riTags = new RepositoryItemCheckedComboBoxEdit();
        void InitCheckedComboBox()
        {
            ds.ProductTag.Clear();
            GetDetails("ProductTag", "GetProductTag");

            riTags.Items.Clear();
            foreach (DataRow dr in ds.ProductTag.Rows)
                riTags.Items.Add(dr["Name"].ToString(), CheckState.Unchecked, dr["ParentId"] != DBNull.Value);
            gvProduct.Columns["Tags"].ColumnEdit = riTags;

            // Specify the separator character.
            //checkedComboBoxEdit1.Properties.SeparatorChar = ';';
            // Set the edit value.
            //checkedComboBoxEdit1.SetEditValue("Circle; Ellipse");
            // Disable the Circle item.
            //checkedComboBoxEdit1.Properties.Items["Circle"].Enabled = false;

            //List<Record> data = GetData();
            //List<Item> items = GetItems();

            //checkedComboBoxEdit1.DataBindings.Add("EditValue", data, "Days");
            //checkedComboBoxEdit1.Properties.DataSource = items;
            //checkedComboBoxEdit1.Properties.DisplayMember = "Description";
            //checkedComboBoxEdit1.Properties.ValueMember = "Value"; 

            //[FlagsAttribute]
            //enum Colors { None = 0, Red = 1, Green = 2, Blue = 4, Yellow = 8, Black = 16 };

            //checkedComboBoxEdit1.Properties.SetFlags(typeof(Colors));
            //checkedComboBoxEdit1.SetEditValue(Colors.Red | Colors.Blue | Colors.Yellow);

        }


        int ProductId;
        void barManager_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "&Tarayıcı Seç":
                        Scanner.OpenDeviceDialog();
                        break;

                    case "&Etiket Düzenle":
                        using (ProductTag productTag = new ProductTag())
                            productTag.ShowDialog();

                        InitCheckedComboBox();
                        break;
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        void Product_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
            //e.Row["StokTipiId"] = (int)StokTipi.Kumas;
        }

        private void BtnScan_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (bsProduct.Count > 0)
            {
                if (gvProduct.GetFocusedRowCellValue("Scan") != null)
                    if (XtraMessageBox.Show("Bu varyant için daha önce taranmış bir görüntü var. Üzerine yazmak ister misiniz?", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;

                Scan();
            }
        }

        Scanner.PhotosTable photosTable = new Scanner.PhotosTable();

        void Scan(bool big = false)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                Save();

                Image scanned = Scanner.Scan(big);    //kumaş için sabitlendi

                // scanned = Image.FromFile("d:\\Article_16.png");

                //byte[] bytes =  File.ReadAllBytes("d:\\test.pmg");
                //i0 = i2 = Image.FromFile("d:\\test.png");

                if (scanned != null)
                {
                    ProductId = intParse(bsProduct, "ProductId");

                    //if (Directory.Exists(@"C:\Tarama"))
                    //{
                    //    scanned.Save(@"C:\Tarama\" + intParse(bsProduct, "ProductId").ToString() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".png", ImageFormat.Png);
                    //    scanned.Save(@"C:\Tarama\" + intParse(bsProduct, "ProductId").ToString() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".jpg", ImageFormat.Jpeg);
                    //}

                    DataRow dr = photosTable.AddRow(ProductId, scanned, big);
                    AppSession.Lookups.V_Kumas.FindByProductId(ProductId).PhotoMikro = (byte[])dr["Photo1"];
                    gvProduct.InvalidateRow(gvProduct.FocusedRowHandle);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        int SaveCount = 0;
        private void BtnKaydet_ItemClick(object sender, ItemClickEventArgs e)
        {
            btnKaydet.Enabled = false;
            Save();

            //TODO: normal taramanın üstüne BIG tarayınca big flag'ini setlemiyor!
            ExecuteNonQuery("UpdPhoto6", photosTable.Table, Environment.MachineName);

            //ds.xPhoto5.Clear();

            if ((++SaveCount) % 5 == 0)
                GC.Collect();

            photosTable = new Scanner.PhotosTable();

            //string serializedPic = XML.SerializePic(ds.xPhoto5);
            //ByteArray string e çevrildiği için 3,5MB yaklaşık 5MB oluyor. Eğer resimler tek tek sp'ye byte array olarak gönderilirse hızlandırılabilir.

            //http://forums.asp.net/t/1417349.aspx/1
            //http://entlib.codeplex.com/workitem/28231

            btnKaydet.Enabled = true;
            RefreshData();
            Notify("Kaydedildi");
        }

        //void UpdPhoto6(params object[] p)
        //{
        //    using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
        //    {
        //        sqlConn.Open();
        //        SqlCommand sqlCmd = sqlConn.CreateCommand();
        //        sqlCmd.CommandText = "UpdPhoto6";
        //        sqlCmd.CommandType = CommandType.StoredProcedure;
        //        SqlParameter[] parameters = new SqlParameter[2];
        //        parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
        //        parameters[0].Value = p[0];
        //        parameters[1] = new SqlParameter("@DeviceID", SqlDbType.VarChar);
        //        parameters[1].Value = p[1];
        //        sqlCmd.Parameters.AddRange(parameters);
        //        sqlCmd.ExecuteNonQuery();
        //    }
        //}

        private void Git(int productId)
        {
            gvProduct.FocusedRowHandle = gvProduct.LocateByValue("ProductId", productId);
            gvProduct.MakeRowVisible(gvProduct.FocusedRowHandle);
        }


        private void BtnKartAc_ItemClick(object sender, ItemClickEventArgs e)
        {
            using (DesenAra desenAra = new DesenAra())
            {
                DialogResult dr = desenAra.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    Git(desenAra.ProductId);
                }
                else if (dr == DialogResult.No)
                {
                    MyData.ProductRow pr = ds.Product.NewProductRow();
                    pr.Name = desenAra.DesenNo;
                    ds.Product.AddProductRow(pr);
                    Save();
                    gvProduct.MoveLast();
                    AppSession.MainForm.RefreshData();
                }

            }
        }


    }
}